package com.budwk.app.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.budwk.app.waterquality.config.AppException;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;

@Slf4j
public class PoiUtil {

    public static String getDownFileUrl(String fileName, SXSSFWorkbook book, HttpServletResponse response) {
        try {
            String fileDownPath = "/upload/" + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN) + "/"; // 文件存储路径
            String fileDirectory = NutzIocUtils.getUploadPath() + fileDownPath; // 文件存储目录
            File file = new File(fileDirectory);
            if (!file.exists()) {
                file.mkdirs();
            }
            String filePath = fileDirectory + fileName;
            FileOutputStream out = new FileOutputStream(filePath);
            book.setCompressTempFiles(true);
            book.write(out);
            out.close();
            response.flushBuffer();
            book.dispose();  //临时文件需要手动显式
            String url = fileDownPath + fileName;
            String absUrl = "http://127.0.0.1:18285/api" + url;
            log.info("downStatReport res : {}", absUrl);
            return url;
        } catch (Exception e) {
            throw new AppException("文件下载失败！");
        }
    }

    public static InputStream getInputStream(String filePath) {
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            if(!classPathResource.exists()){
                throw new AppException("文件不存在:{}"+filePath);
            }
            return classPathResource.getInputStream();
        } catch (Exception e) {
            log.error("getInputStream error:", e);
            throw new AppException("文件异常:{}"+filePath);
        }
    }

    public static CellStyle getCellStyle(SXSSFWorkbook book) {
        CellStyle cellStyle = book.createCellStyle();
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左边框
        cellStyle.setBorderTop(BorderStyle.THIN);//上边框
        cellStyle.setBorderRight(BorderStyle.THIN);//右边框
        cellStyle.setWrapText(true); //设置自动换行
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 设置单元格水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格垂直居中
        return cellStyle;
    }
}
